import React, { useEffect, useMemo, useState } from 'react';
import { Button, Checkbox, Input, Modal, Select } from 'antd';
import { GetFolderPropertyVerStrategy, getProcessStrategy } from '../../services';
import { TextWidget, getMessage } from '@inbiz/react';
import { getPath, splitFileName } from '../../utils/tool';
import { strategyList } from '../../utils/shared';
import { getFileTypeIcon } from '@inbiz/utils';

const { Option } = Select;
const StrategyModal = (props: any) => {
  const { file, onClose, folderId, events, uploader, onStrategyList, onStrategyFileNameFormat } = props;
  const { name } = splitFileName(file.filename);
  const strategyFileName = onStrategyFileNameFormat?.(file?.filename, file) || file.filename
  const [options, setOptions] = useState<{ label: string; value: string }[]>(
    [],
  );
  const [strategy, setStrategy] = useState('');
  const [path, setPath] = useState('');
  const [newName, setNewName] = useState(`${name}(1)`);
  const [checked, setChecked] = useState(false);
  const [visible, setVisible] = useState(true);
  const onOk = () => {
    if (strategy === 'rename' && (!newName || newName === name)) return;
    const data = {
      strategy,
      newName: strategy === 'rename' ? newName : '',
      checked,
      folderId,
    };
    onClose(data);
    setVisible(false);
  };
  const onCancel = () => {
    const data = {
      strategy: '',
      newName: '',
      checked: false,
    };
    onClose(data);
    setVisible(false);
  };

  /**
   * 获取ECM设置的文件夹策略，根据返回的VersionType和overlayStrategy字段，过滤后得到策略列表
   * 获取流程策略，如果有启用流程策略，则过滤策略
   * @param folderId 文件夹id
   *
   */
  const getFolderStrategy = async (folderId: string) => {
    const params = uploader.methods._paramsStore.get(file?.id);
    const data = await GetFolderPropertyVerStrategy(folderId);
    const result = await getProcessStrategy({ folderIds: [folderId] }, 2)
    const { VersionType, overlayStrategy } = data?.verStrategy || {};
    const filetrType = strategyList.filter(
      (item) => !(item?.type && item?.type.includes(VersionType)),
    );
    const filterOverlay = filetrType.filter(
      (item) => !(item?.overlay && item?.overlay.includes(overlayStrategy)),
    );
    let options = filterOverlay.map((item) => {
      return {
        label: getMessage(`inbizUpload.${item.label}`),
        value: item.value,
      };
    })
    /**
     * 1. 根据流程策略的IsProcessStrategy字段，来判断是否过滤
     * 2. folderId为3时，且上传的文件参数有masterFileId时，则是上传附件，重名策略默认只有重命名和跳过
     */
    if (result?.IsProcessStrategy || (folderId == '3' && params?.masterFileId)) {
      options = options.filter(
        (item) => (item?.value == 'rename' || item?.value == 'skip')
      )
    }
    const newOptions = onStrategyList?.(folderId, options) || options;
    // 提供方法更改策略配置，及默认选中项
    const strategy: {
      options: { label: string; value: string }[]
      select: string
    } = await events?.current?.onStrategyFormat?.({
      file,
      options: newOptions,
      select: newOptions[0]?.value
    }) ?? {
        options: newOptions,
        select: newOptions[0]?.value
      }
    //转换多语言，外部传入多语言key的情况下
    strategy.options = strategy.options.map(item => {
      return {
        ...item,
        label: getMessage(item.label)
      }
    })
    setStrategy(strategy.select);
    setOptions(strategy.options);
  };
  useEffect(() => {
    if (folderId) {
      getPath(folderId).then((res: string) => {
        const newPath: string = getMessage('inbizUpload.folder') + res + getMessage('inbizUpload.strategy');
        setPath(newPath)
      })
      getFolderStrategy(folderId);
    }
  }, [folderId]);

  return (
    <Modal
      title={getMessage('inbizUpload.fileRename')}
      visible={visible}
      onCancel={onCancel}
      maskClosable={false}
      className="react-fine-uploader-strategy-modal"
      footer={[
        <Button type="primary" onClick={onOk} key="okModal">
          <TextWidget>inbizUpload.ok</TextWidget>
        </Button>
      ]}
    >
      <div>
        <div className="react-fine-uploader-strategy-modal-filename">
          <span className="react-fine-uploader-strategy-modal-content-file-label">
            {/* <TextWidget>inbizUpload.file_rename</TextWidget> */}
            <img src={getFileTypeIcon(file.filename)} />
          </span>

          <span className="react-fine-uploader-strategy-modal-content-file" title={strategyFileName}>
            {strategyFileName}
          </span>
        </div>
        <div>
          <span className="react-fine-uploader-strategy-modal-content-strategy-label">
            <TextWidget>inbizUpload.renameStrategy</TextWidget>
          </span>
          <Select
            className="react-fine-uploader-strategy-modal-content-strategy"
            value={strategy}
            onSelect={(value: string) => setStrategy(value)}
          >
            {options.map((option) => (
              <Option value={option.value} key={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        </div>
        <div className="react-fine-uploader-strategy-modal-content-rename">
          {strategy === 'rename' ? (
            <div className="react-fine-uploader-strategy-modal-content-newname">
              <span className="react-fine-uploader-strategy-modal-content-newname-label">
                <span className='react-fine-uploader-strategy-modal-content-newname-label-asterisk'>*</span>
                <TextWidget>inbizUpload.renamefore</TextWidget>
              </span>
              <Input
                status={newName && newName !== name ? '' : 'error'}
                value={newName}
                onChange={(e) => setNewName(e.target.value)}
                style={{ width: '100%' }}
                className="react-fine-uploader-strategy-modal-content-input"
              />
              {(!newName || newName === name) && (
                <div className="react-fine-uploader-strategy-modal-content-newname-error">
                  {newName
                    ? getMessage('inbizUpload.renameError')
                    : getMessage('inbizUpload.nullNameError')}
                </div>
              )}
            </div>
          ) : (
            <div className="react-fine-uploader-strategy-modal-content-check">
              <Checkbox
                checked={checked}
                onChange={(e) => setChecked(e.target.checked)}
              />
              <span className="react-fine-uploader-strategy-modal-content-check-title" title={path}>
                {path}
              </span>
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
};

export default StrategyModal;
